<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片信息 -->
        <el-card>
            <!-- 数据搜索及数据添加 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容"  class="input-with-select" v-model="requiredparameter.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="UserDialogFormVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <!-- 用户信息表单区 -->
            <el-table :data="userlist" border stripe>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column label="姓名" prop='username'></el-table-column>
                <el-table-column label="电话" prop='mobile'></el-table-column>
                <el-table-column label="邮箱" prop='email'></el-table-column>
                <el-table-column label="角色" prop='role_name'></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                    <template slot-scope="scope">
                        <!-- 修改用户信息 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="modifyOldUser(scope.row.id)"></el-button>
                        <!-- 删除用户 -->
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeOldUser(scope.row.id)"></el-button>
                        <!-- 管理用户权限 -->
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showDistributeRoles(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页栏 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="requiredparameter.pagenum" :page-sizes="[1,2, 4, 8, 10]" :page-size="requiredparameter.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="totalpage">
            </el-pagination>
        </el-card>

        <!-- 添加用户信息对话框 -->
        <el-dialog title="添加用户" :visible.sync="UserDialogFormVisible" @close="UserDialogClose" width="50%">
            <el-form :model="addform" :rules="addformrules" ref="addformRef" label-width="100px" status-icon>
                <el-form-item label="用户名：" prop="username">
                    <el-input v-model="addform.username"></el-input>
                </el-form-item>
                <el-form-item label="密码：" prop="password">
                    <el-input v-model="addform.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱：" prop="email">
                    <el-input v-model="addform.email"></el-input>
                </el-form-item>
                <el-form-item label="手机：" prop="mobile">
                    <el-input v-model="addform.mobile"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="UserDialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addNewUser">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 修改用户信息对话框 -->
        <el-dialog title="修改用户" :visible.sync="modifyDialogForm" width="50%" @close="modifyDialogClose">
            <el-form :model="modifyForm" :rules="modifyFormRules" ref="modifyFormRef" label-width="100px" status-icon>
                <el-form-item label="用户名：">
                    <el-input v-model="modifyForm.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱：" prop="email">
                    <el-input v-model="modifyForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机：" prop="mobile">
                    <el-input v-model="modifyForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="modifyDialogForm = false">取 消</el-button>
                <el-button type="primary" @click="modifyNewUser">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 角色分配对话框 -->
        <el-dialog title="提示" :visible.sync="showDistributeDialogVisible" width="50%" @close="emptyRolesDialog">
          <div>
            <p>当前的用户：{{this.userInfo.username}}</p>
            <p>当前的角色：{{this.userInfo.role_name}}</p>
            <p>要分配的角色：
              <el-select v-model="modifyRolesPower" placeholder="请选择">
                <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
                </el-option>
              </el-select>
          </p>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="showDistributeDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="modifyNewRolesPower">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    //   自定义校验规则
    var checkEmail = (rule, value, callback) => {
      const regemail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (regemail.test(value)) {
        callback()
      }
      callback(new Error('邮箱输入错误!'))
    }
    var checkMobile = (rule, value, callback) => {
      const regmobile = /((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/
      if (regmobile.test(value)) {
        callback()
      }
      callback(new Error('手机号输入错误!'))
    }
    return {
      // 查询用户的提交信息
      requiredparameter: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userlist: [],
      totalpage: 0,
      //   控制用户添加对话框的显示与隐藏
      UserDialogFormVisible: false,
      //   添加用户表单信息
      addform: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //   添加用户表单验证
      addformrules: {
        username: [{ required: true, message: '请输入登录名称', trigger: 'blur' }, {
          min: 2,
          max: 10,
          message: '长度在 2 到 10 个字符',
          trigger: 'blur'
        }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 16,
            message: '长度在 6 到 16 个字符',
            trigger: 'blur'
          }],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }, { validator: checkEmail, trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }, { validator: checkMobile, trigger: 'blur' }]
      },
      //   控制修改用户对话框显示与隐藏
      modifyDialogForm: false,
      //   修改用户表单信息
      modifyForm: {},
      //   修改用户表单验证
      modifyFormRules: {
        email: [
          { required: true, message: '请输入邮箱！', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' }, { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 角色分配对话框的显示与隐藏
      showDistributeDialogVisible: false,
      // 用户信息
      userInfo: {},
      // 所有角色列表
      rolesList: {},
      // 修改后的权限
      modifyRolesPower: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    //  获取用户数据
    async getUserList() {
      const { data: res } = await this.$http.get('/users', { params: this.requiredparameter })
      if (res.meta.status !== 200) {
        return this.$message({
          showClose: true,
          message: res.meta.msg,
          type: 'error'
        })
      }
      this.userlist = res.data.users
      this.totalpage = res.data.total
    },
    // 每页多少条用户信息
    handleSizeChange(newPagesize) {
      this.requiredparameter.pagesize = newPagesize
      this.getUserList()
    },
    // 当前在第几页
    handleCurrentChange(newPagenum) {
      this.requiredparameter.pagenum = newPagenum
      this.getUserList()
    },
    // 修改当前用户状态
    async changeUserState(val) {
      const { data: res } = await this.$http.put(`users/${val.id}/state/${val.mg_state}`)
      if (res.meta.status !== 200) {
        val.mg_state = !val.mg_state
        return this.$message({
          showClose: true,
          message: '修改用户状态失败！',
          type: 'error'
        })
      }
      this.$message({
        showClose: true,
        message: res.meta.msg,
        type: 'success'
      })
    },
    // 清空添加用户对话框内容
    UserDialogClose() {
      this.$refs.addformRef.resetFields()
    },
    // 点击确定按钮，添加新用户
    addNewUser() {
      // 先进行表单的预校验
      this.$refs.addformRef.validate(async val => {
        if (!val) {
          return this.$message({
            showClose: true,
            message: '添加用户信息失败！',
            type: 'error'
          })
        }
        // 发起网络请求，添加用户
        const { data: res } = await this.$http.post('/users', this.addform)
        if (res.meta.status !== 201) {
          return this.$message({
            showClose: true,
            message: res.meta.msg,
            type: 'error'
          })
        }
        this.$message({
          showClose: true,
          message: '添加用户信息成功！',
          type: 'success'
        })
        this.getUserList()
        this.UserDialogFormVisible = false
      })
    },
    // 修改用户信息
    async modifyOldUser(id) {
      // 获取用户信息
      const { data: res } = await this.$http.get('/users/' + id)
      if (res.meta.status !== 200) {
        return this.$message({
          showClose: true,
          message: res.meta.msg,
          type: 'error'
        })
      }
      console.log(res)
      this.modifyForm = res.data
      this.modifyDialogForm = true
    },
    // 重置修改用户信息对话框
    modifyDialogClose() {
      this.$refs.modifyFormRef.resetFields()
    },
    // 确认修改用户信息
    modifyNewUser() {
      this.$refs.modifyFormRef.validate(async val => {
        if (!val) return
        // 发起网络请求，修改用户信息
        const { data: res } = await this.$http.put('/users/' + this.modifyForm.id, { email: this.modifyForm.email, mobile: this.modifyForm.mobile })
        if (res.meta.status !== 200) {
          return this.$message({
            showClose: true,
            message: res.meta.msg,
            type: 'error'
          })
        }
        // 刷新用户列表数据
        this.getUserList()
        // 关闭对话框
        this.modifyDialogForm = false
        // 显示修改用户成功
        this.$message({
          showClose: true,
          message: '用户信息修改成功！',
          type: 'success'
        })
      })
    },
    // 点击删除按钮判断是否确认删除用户信息
    async removeOldUser(id) {
      const removeInfo = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (removeInfo !== 'confirm') {
        return this.$message({
          showClose: true,
          message: '删除用户操作已取消！',
          type: 'info'
        })
      } else {
        const { data: res } = await this.$http.delete('/users/' + id)
        if (res.meta.status !== 200) {
          return this.$message({
            showClose: true,
            message: res.meta.msg,
            type: 'error'
          })
        }
        this.getUserList()
        this.$message({
          showClose: true,
          message: '删除用户成功！',
          type: 'success'
        })
      }
    },
    // 展示角色分配对话框
    async showDistributeRoles(userinfo) {
      this.userInfo = userinfo
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) {
        return this.$message({
          showClose: true,
          message: '获取角色列表失败！',
          type: 'error'
        })
      }
      this.rolesList = res.data
      this.showDistributeDialogVisible = true
    },
    // 点击确认修改当前用户角色
    async modifyNewRolesPower() {
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.modifyRolesPower })
      if (res.meta.status !== 200) {
        return this.$message({
          showClose: true,
          // message: '修改用户角色失败！',
          message: res.meta.msg,
          type: 'error'
        })
      }
      this.$message({
        showClose: true,
        message: res.meta.msg,
        type: 'success'
      })
      this.getUserList()
      this.showDistributeDialogVisible = false
    },
    // 清空角色管理对话框
    emptyRolesDialog() {
      this.modifyRolesPower = ''
      this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
.el-table {
    margin-top: 20px;
}
.el-pagination{
    margin-top: 20px;
}
</style>
